<template>
  <div class="extend-panel-table" style="height: 100%">
    <je-table
      ref="xExtendTable"
      stripe
      auto-resize
      sync-resize
      show-overflow
      keep-source
      show-header-overflow
      resizable
      header-align="center"
      align="center"
      :data="tableData"
      draggable
      height="100%"
      :edit-rules="validRules"
      :edit-config="{
        trigger: 'click',
        mode: 'cell',
        showUpdateStatus: true,
        showStatus: false,
      }"
      size="mini"
      @cell-click="onClickRow"
      @drop="dropTable"
    >
      <je-table-column width="40">
        <template #header>
          <i style="font-size: 16px; cursor: pointer" class="fal fa-plus" @click="addColumn"></i>
        </template>
        <template #default="{ row }">
          <i
            style="font-size: 16px; cursor: pointer"
            class="fal fa-times"
            @click="deleteColumn(row)"
          ></i>
        </template>
      </je-table-column>
      <je-table-column
        v-if="tabType == 'single'"
        title="位置"
        field="location"
        :edit-render="{}"
        width="140"
        name="location"
      >
        <template #header>
          <div>
            位置
            <i
              class="fas fa-question-circle"
              style="color: #c0c4cc"
              :style="changeColor(unitTipShow)"
              @click="clickIcon('location')"
              @mouseenter="unitTipShow = true"
              @mouseleave="unitTipShow = false"
            />
          </div>
          <div v-if="tipShow">
            <tip-view :visble="tipShow" :type="tipType" @changeTipShow="tipShow = false"></tip-view>
          </div>
        </template>
        <template #default="{ row }">
          {{ formateType(row.location, locationData) }}
        </template>
        <template #edit="{ row }">
          <je-select
            v-model:value="row.location"
            type="text"
            :options="locationData"
            @change="selectData(row)"
          ></je-select>
        </template>
      </je-table-column>
      <je-table-column
        title="名称"
        field="text"
        :edit-render="{ autofocus: '.ant-input' }"
        width="140"
        name="text"
      >
        <template #edit="{ row }">
          <je-input v-model:value="row.text" type="text"></je-input>
        </template>
      </je-table-column>
      <je-table-column
        title="编码"
        field="code"
        :edit-render="{ autofocus: '.ant-input' }"
        width="220"
        name="code"
      >
        <template #edit="{ row }">
          <je-input v-model:value="row.code" type="text"></je-input>
        </template>
      </je-table-column>
      <je-table-column title="类型" :edit-render="{}" width="140" field="type" name="type">
        <template #default="{ row }">
          {{ formateType(row.type, typeData) }}
        </template>
        <template #edit="{ row }">
          <je-select
            v-model:value="row.type"
            :options="typeData"
            @change="changeType(row.type, row)"
          />
        </template>
      </je-table-column>
      <je-table-column
        v-if="tabType == 'double'"
        title="扩展位置"
        :edit-render="{}"
        width="140"
        field="extendLocation"
        name="extendLocation"
      >
        <template #default="{ row }">
          {{ formateType(row.extendLocation, extendData) }}
        </template>
        <template #edit="{ row }">
          <je-select
            v-model:value="row.extendLocation"
            :options="extendData"
            @change="changeType(row.extendLocation, row)"
          />
        </template>
      </je-table-column>
      <je-table-column
        title="配置信息"
        :edit-render="{ autofocus: '.ant-input' }"
        min-width="140"
        field="configInfo"
        name="configInfo"
      >
        <template #edit="{ row }">
          <div v-if="row.type == 'chart' || row.type == 'report'">
            <je-tree-select
              v-model:value="row.configInfo"
              name="configInfo"
              :config-info="configInfoStr"
              :orders="[{ code: 'SY_ORDERINDEX', type: 'ASC' }]"
              @select="selectFunc"
            />
          </div>
          <div v-else-if="row.type == 'plugin'">
            <je-grid-select
              v-model:value="row.configInfo"
              name="configInfo"
              :config-info="configInfoStr"
              :orders="[{ code: 'SY_ORDERINDEX', type: 'ASC' }]"
            />
          </div>
          <div v-else>
            <je-input v-model:value="row.configInfo" type="text"></je-input>
          </div>
        </template>
      </je-table-column>
      <je-table-column
        width="100"
        field="height"
        :edit-render="{ autofocus: '.ant-input' }"
        name="height"
      >
        <template #header>
          <div>
            <span v-if="tabType == 'double'">宽度</span>
            <span v-else>
              宽/高
              <i
                class="fas fa-question-circle"
                style="color: #c0c4cc"
                :style="changeColor(unitTipHeightShow)"
                @click="clickIcon('height')"
                @mouseenter="unitTipHeightShow = true"
                @mouseleave="unitTipHeightShow = false"
              />
            </span>
          </div>
        </template>
        <template #edit="{ row }">
          <je-input v-model:value="row.height" type="text"></je-input>
        </template>
      </je-table-column>
      <je-table-column
        v-if="tabType == 'double'"
        name="active"
        title="启用"
        width="80"
        field="active"
        type="switch"
      >
      </je-table-column>
    </je-table>
  </div>
</template>

<script>
  import { defineComponent, onMounted, reactive, toRefs, watch, defineAsyncComponent } from 'vue';
  import { Grid, Modal, InputSelect, Input, Select } from '@jecloud/ui';
  import VueEvent from '@/helper/event';
  export default defineComponent({
    name: 'ExtendPanel',
    components: {
      JeInput: Input,
      JeSelect: Select,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JeTreeSelect: InputSelect.Tree,
      JeGridSelect: InputSelect.Grid,
      TipView: defineAsyncComponent(() => import('./tipview.vue')),
    },
    props: {
      extentType: String,
      extendTableData: Array,
      refObj: String,
    },
    emits: ['changeData', 'checkTableResult', 'changeActiveStatu'],
    setup(props, { emit }) {
      const state = reactive({
        xExtendTable: '',
        typeData: [
          { label: '插件', value: 'plugin' },
          { label: 'html', value: 'html' },
          { label: '链接', value: 'link' },
          // { label: '图表', value: 'chart' },
          // { label: '报表', value: 'report' },
          // { label: '门户', value: 'portal' },
        ],
        locationData: [
          { label: '外部上方', value: 'outTop' },
          { label: '外部下方', value: 'outBottom' },
          { label: '外部左方', value: 'outLeft' },
          { label: '外部右方', value: 'outRight' },
          { label: '列表上方', value: 'listTop' },
          { label: '列表下方', value: 'listBottom' },
          { label: '列表左方', value: 'listLeft' },
          { label: '列表右方', value: 'listRight' },
        ],
        extendData: [
          {
            label: '列表',
            value: 'list',
          },
          {
            label: '表单',
            value: 'form',
          },
        ],
        tabType: props.extentType,
        configInfoStr: '',
        validRules: {
          configInfo: [{ required: true, message: '该输入项为必填项' }],
          height: [{ required: true, message: '该输入项为必填项' }],
          text: [{ required: true, message: '该输入项为必填项' }],
          code: [{ required: true, message: '该输入项为必填项' }],
          location: [{ required: true, message: '该输入项为必填项' }],
          type: [{ required: true, message: '该输入项为必填项' }],
          extendLocation: [{ required: true, message: '该输入项为必填项' }],
        },
        tipShow: false,
        unitTipShow: false,
        unitTipHeightShow: false,
        tipType: '',
      });

      // 查询参数table增加
      const addColumn = async () => {
        const $table = state.xExtendTable;
        const record = {
          location: '', // 位置
          text: '', // 名称
          code: '', //编码
          configInfo: '', // 配置信息
          height: '200', // 宽/高
          type: '', //类型
          active: '0', // 启用
          extendLocation: props.extentType == 'single' ? 'list' : '', // 扩展位置
          extentType: props.extentType,
          index: state.tableData.length + 1,
        };
        await $table.insertAt(record, -1);
        emit('changeData', $table.getTableData().tableData);
      };
      const methods = {
        dropTable() {
          const data = state.xExtendTable.getTableData().tableData;
          data.forEach((item, index_) => {
            item.index = index_;
          });
          state.tableData = data;
          emit('changeData', data);
        },
        // 改变tip浮上去的颜色
        changeColor(flag) {
          if (flag) {
            return 'cursor:pointer;color: #3265F5';
          }
          return 'cursor:pointer;';
        },
        selectData(row) {
          const data = state.xExtendTable.getTableData().tableData;
          const arr = data.filter((item) => item.location == row.location);
          if (arr && arr.length > 1) {
            row.location = '';
            Modal.alert('您所选的方位最多只能添加一条数据!', 'warning');
            return false;
          }
        },
        checkForm() {
          if (!state.xExtendTable) return false;
          const $table = state.xExtendTable.$plugin;
          const data = $table.getTableData().tableData;
          $table.validate(data, (errMap) => {
            if (errMap) {
              emit('checkTableResult', false);
            } else {
              emit('checkTableResult', true);
            }
          });
        },

        selectFunc({ rows }) {
          if (rows && rows.length) {
            // 这边要处理一个逻辑就是当选择的不是叶子节点的时候，要给弹窗
            const { leaf } = rows[0];
            if (!leaf) {
              Modal.alert('请选择正确的数据', 'info');
              return false;
            }
          }
        },
        // 当类型进行改变的时候，要将配置信息的查询选择configInfo进行赋值
        changeType(value, row) {
          row.configInfo = '';
          // 图表
          if (value == 'chart') {
            state.configInfoStr = 'JE_CORE_CHARTS,configInfo,code,S';
          } else if (value == 'report') {
            // 报表
            state.configInfoStr = 'JE_CORE_REPORT,configInfo,code,S';
          } else if (value == 'plugin') {
            // 插件
            state.configInfoStr = 'JE_META_MICROAPP,configInfo,MICROAPP_CODE,S';
          } else {
            state.configInfoStr = '';
          }
        },
        // 格式化类型
        formateType(value, data) {
          // if (!value) return '';
          const formatItem = data.find((item) => {
            if (item.value == value) {
              return item;
            }
          });
          return formatItem ? formatItem.label : '';
        },
        // 查询参数table删除
        deleteColumn(record) {
          const $table = state.xExtendTable.$plugin;
          $table.remove(record);
          emit('changeData', $table.getTableData().tableData);
        },
        clickIcon(type) {
          state.tipShow = true;
          state.tipType = type;
        },
      };
      watch(
        () => props.extendTableData,
        (val) => {
          const tableData = val.filter((item) => item.extentType == state.tabType);
          const arr = [];
          tableData.forEach((item) => {
            if (state.tabType == 'double') {
              delete item.location;
            }
            const flag = Object.values(item).some((itemKey) => !itemKey);
            arr.push(flag);
          });
          emit('changeActiveStatu', { flag: arr.some((itemKey) => itemKey), type: state.tabType });
        },
        { deep: true, immediate: true },
      );
      watch(
        () => state.tabType,
        (val) => {
          state.tableData = props.extendTableData.filter((item) => item.extentType == val);
          if (val == 'single') {
            state.validRules.location = [{ required: true, message: '该输入项为必填项' }];
          } else {
            state.validRules.location = [{ required: false }];
          }
          VueEvent.off('checkedMenu');
        },
        { deep: true, immediate: true },
      );
      onMounted(() => {
        VueEvent.on('checkedMenu', (flag) => {
          flag && methods.checkForm();
        });
      });
      return {
        addColumn,
        ...methods,
        ...toRefs(state),
      };
    },
  });
</script>
